package com.cms.intelligent_control.app

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.cms.intelligent_control.R
import com.cms.intelligent_control.audio.AudioRecorder
import com.cms.intelligent_control.common.event.PlayCompletionEvent
import com.cms.intelligent_control.config.Config
import com.cms.intelligent_control.common.websocket.WebSocketHelper
import com.cms.intelligent_control.instructions.AudioVideoCmd
import com.cms.intelligent_control.instructions.MonitorListCmd
import com.cms.intelligent_control.module.BrowserModule
import com.cms.intelligent_control.module.CommonModule
import com.cms.intelligent_control.module.VideoModule
import com.cms.intelligent_control.utils.isJsonStr
import com.tbruyelle.rxpermissions2.RxPermissions
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject


class MainActivity : AppCompatActivity() {

    private val rxPermissions by lazy { RxPermissions(this) }
    private val audioRecorder by lazy {
        AudioRecorder(this)
    }
    private val webSocketHelper by lazy {
        WebSocketHelper(Config.baseWsUrl + "websocketist/jsjddjajdh/iat")
    }


    private lateinit var mVoiceTextView: TextView

    private lateinit var mBrowserModule: BrowserModule
    private lateinit var mCommonModule: CommonModule
    private lateinit var mVideoModule: VideoModule
    private lateinit var mAudioVideoCmd: AudioVideoCmd
    private lateinit var mMonitorListCmd: MonitorListCmd

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViews()
        requestPermission()

        initModule()

    }

    private fun initViews() {
        mVoiceTextView = findViewById(R.id.voice_text)
        Glide.with(this).load(R.mipmap.elfish_active).into(findViewById(R.id.iv_elfish))
    }

    private fun initModule() {
        mCommonModule = CommonModule(this)
        mBrowserModule = BrowserModule(this)
        mVideoModule = VideoModule(this)

        mAudioVideoCmd = AudioVideoCmd(this, mVideoModule)
        mMonitorListCmd = MonitorListCmd(this, mVideoModule)
    }

    private fun handleAction(result: String) {
        if (!mCommonModule.isActive()) {
            return
        }
        if (!isJsonStr(result)) {
            mVoiceTextView.text = result
            mAudioVideoCmd.executeLocalCmd(result)
            mMonitorListCmd.executeLocalCmd(result)
            return
        }
        val obj = JSONObject(result)
        mCommonModule.startTts(obj)
        if (obj["status"] == 0) {
            val data = obj.optJSONArray("data").optJSONObject(0)
            if (mVideoModule.intercept(data)) {
                return
            }

            if (mCommonModule.isCommonAction(data)) {
                mCommonModule.execute(data)
                mAudioVideoCmd.hideAudioVideoList()
                mMonitorListCmd.hideMonitorList()
            }

            if (mBrowserModule.isBrowserAction(data)) {
                mBrowserModule.execute(data)
                mAudioVideoCmd.hideAudioVideoList()
                mMonitorListCmd.hideMonitorList()
            }

            if (mVideoModule.isAudioVideoAction(data)) {
                mVideoModule.execute(data)
                mAudioVideoCmd.hideAudioVideoList()
                mMonitorListCmd.hideMonitorList()
            }

            if (mAudioVideoCmd.isAudioVideoListAction(data)) {
                mAudioVideoCmd.execute(data)
            }
            if (mMonitorListCmd.isMonitorListAction(data)) {
                mMonitorListCmd.execute(data)
            }
        }
    }


    private fun requestPermission() {
        val d = rxPermissions.request(
            Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe {
            if (it) {
                initAudioRecorder()
                audioRecorder.startRecord()
            } else {
                Toast.makeText(this, "请授权录音权限！", Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }

    private fun initAudioRecorder() {
        audioRecorder.createDefaultAudio("Temp")
        audioRecorder.setRecordStreamListener(object : AudioRecorder.RecordStreamListener {
            override fun onStart() {
                initWebSocket()
            }

            override fun onRecord(data: ByteArray, length: Int) {
                webSocketHelper.sendData(data)
            }
        })
    }

    private fun initWebSocket() {
        webSocketHelper.start {
            onMessage { msg ->
                Log.d("MainActivity", "WebSocket onMessage $msg")
                handleAction(msg)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: PlayCompletionEvent) {
        mAudioVideoCmd.onPlayCompletion()
    }

    override fun onDestroy() {
        super.onDestroy()
        audioRecorder.release()
        webSocketHelper.close()
        mVideoModule.destroy()
    }

}